import router from '@/router'
import { asyncAppRouter } from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from "@/utils/auth";


const whiteList = ['/login', '/authredirect'] //不重定向的白名单

router.beforeEach((to, from, next) => {
    NProgress.start() //开启NProgress进度条

    if(getToken()) {    //判断是否有token
        if(to.path === '/login') {  //如果token存在并且当前页面是login则直接重定向到主页
           next({path: '/'})
        } else {

            //判断当前用户是否已拉取完user_info信息
            if(store.getters.user.account === null) {
                //拉取user_info
                store.dispatch('GetUserInfo').then(res => {
                    // 生成可访问的路由表
                    store.dispatch('GeneratorRouters', asyncAppRouter).then(() => {
                        router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                        next(...to)
                    })

                    next(...to) // hack方法 确保addRoutes已完成

                    store.dispatch('ReloadVisitedViews').then(()=>{})
                }).catch(() => {
                    //如果拉取user_info失败，则重定向到登录页面
                    store.dispatch('FedLogOut').then(() => {
                        next({ path: '/login' })
                    })
                })

            } else {
                //验证权限
                next()
            }

        }
    } else {
        if(whiteList.indexOf(to.path) !== -1) { //在免登录白名单中，直接进入
            next()
        } else {
            next('/login')      //否则全部重定向到登录页
            NProgress.done()    //结束NProgress进度条
        }
    }
})

router.afterEach(() => {
    NProgress.done() //结束NProgress进度条
})
